package com.xoa.service.document.Impl;

import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.document.DocumentExchangeReceiveMapper;
import com.xoa.dao.document.DocumentExchangeSetMapper;
import com.xoa.dao.document.DocumentModelMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.document.DocumentExchangeReceive;
import com.xoa.model.document.DocumentExchangeSet;
import com.xoa.model.document.DocumentModelWithBLOBs;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.users.Users;
import com.xoa.service.document.DocumentExchangeReceiveService;
import com.xoa.service.enclosure.EnclosureService;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.util.JAXBSource;
import java.util.*;

@Service
public class DocumentExchangeReceiveServiceImpl implements DocumentExchangeReceiveService {
    @Resource
    private DocumentExchangeReceiveMapper documentReceiveMapper;
    @Resource
    private DocumentExchangeSetMapper documentExchangeSetMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private DocumentModelMapper documentModelMapper;
    @Resource
    private EnclosureService enclosureService;

    //查看某条流程的分发情况
    @Override
    public List<DocumentExchangeReceive> selectByRunId(Integer fromRunId) {
        return documentReceiveMapper.selectByRunId(fromRunId);
    }

    //查看某条流程的分发情况
    @Override
    public int insert(DocumentExchangeReceive documentExchangeReceive) {
        return documentReceiveMapper.insert(documentExchangeReceive);
    }
    //删除多个
    @Override
    public ToJson delete(String receiveIds) {
        ToJson json = new ToJson();
        String[] split = receiveIds.split(",");
        int i = 0;
        try {
            for (String id : split) {
                documentReceiveMapper.deleteByPrimaryKey(Integer.parseInt(id));
                i++;
            }
            json.setMsg("ok");
            json.setFlag(0);
            json.setObject("已删除" + i + "条数据！");
        } catch (Exception e) {
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }
    @Override
    public ToJson<DocumentExchangeReceive> query(PageParams pageParams, HttpServletRequest request) {
        ToJson<DocumentExchangeReceive> json = new ToJson<>();
        String sqlType = "xoa" + (String) request.getSession().getAttribute("loginDateSouse");
        Map<String, Object> map = new HashMap<>();
        String flag = request.getParameter("flag");
        Integer page=(pageParams.getPageSize())*((pageParams.getPage())-1);
        map.put("page", page);
        map.put("pageSize", pageParams.getPageSize());
        map.put("flag", flag);
        DocumentExchangeReceive documentExchangeReceive = new DocumentExchangeReceive();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        String[] deptId = (usersMapper.getByUserId(users.getUserId()).getDeptIdOther()+users.getDeptId()).split(",");
        documentExchangeReceive.setReceiveDeptId(users.getDeptId());
        map.put("deptId", deptId);
        map.put("receiveStatus",request.getParameter("receiveStatus"));
        map.put("docTitle",request.getParameter("docTitle"));
        Map<String, Object> maps = new HashMap<>();
        maps.put("deptId", deptId);
        List<DocumentExchangeSet> documentExchangeSets = documentExchangeSetMapper.selectAll(maps);
        int i=0;
        int x=0;
        for (DocumentExchangeSet documentExchangeSet:documentExchangeSets){
            String[] split = documentExchangeSet.getExchangeUserId().split(",");
            for (String s:split){
                if (users.getUserId().equals(s)){
                    i++;
                }
            }
            String[] split2 = documentExchangeSet.getDocumentPriv().split(",");
            for (String s:split2){
                if ("1".equals(s)){
                    x++;
                }
            }
        }

        List<DocumentExchangeReceive> query=null;
        if (i>0&&x>0){
            query = documentReceiveMapper.query(map);
            for (int e = 0; e < query.size(); e++) {
                DocumentExchangeReceive documentExchangeReceive2 = query.get(e);
                if (documentExchangeReceive2 != null) {
                    if ((!StringUtils.checkNull(documentExchangeReceive2.getReceiveUser())||flag.endsWith("2"))) {
                        String usernameByUserId = usersMapper.getUsernameByUserId(documentExchangeReceive2.getReceiveUser());
                        documentExchangeReceive2.setReceiveUser(usernameByUserId);
                        if(flag.equals("2")){
                            //附件
                            if(documentExchangeReceive2.getAttachmentName()!=null&&documentExchangeReceive2.getAttachmentName()!=""){
                                List<Attachment> attachments = GetAttachmentListUtil.returnAttachment(documentExchangeReceive2.getAttachmentName(), documentExchangeReceive2.getAttachmentId(), sqlType, "workflow");
                                documentExchangeReceive2.setAttachment(attachments);
                            }
                            //正文
                            if(documentExchangeReceive2.getAttachmentName2()!=null&&documentExchangeReceive2.getAttachmentName2()!=""){
                            List<Attachment> attachments2 = GetAttachmentListUtil.returnAttachment(documentExchangeReceive2.getAttachmentName2(), documentExchangeReceive2.getAttachmentId2(), sqlType, "document");
                            documentExchangeReceive2.setAttachment2(attachments2);
                            }
                        }
                    }
                    if ("1".equals(flag)){
                        //附件
                        if(!StringUtils.checkNull(documentExchangeReceive2.getAttachmentId())){
                            List<Attachment> attachments = GetAttachmentListUtil.returnAttachment(documentExchangeReceive2.getAttachmentName(), documentExchangeReceive2.getAttachmentId(), sqlType, "workflow");
                            documentExchangeReceive2.setAttachment(attachments);
                        }
                        if (null != documentExchangeReceive2.getFromRunId()){
                            List attachAndDoc = getAttachAndDoc(sqlType, documentExchangeReceive2.getFromRunId());
                            documentExchangeReceive2.setAttachAndDoc(attachAndDoc);
                        }
                    }
                }
            }
            if(users.getUserPriv().equals(170)||users.getUserPrivOther().contains("170,")){
                json.setObject(true);
            }else {
                json.setObject(false);
            }
            json.setTotleNum(documentReceiveMapper.queryCount(map));
            json.setObj(query);
            json.setFlag(0);
            return json;
        }
        if(users.getUserPriv().equals(170)||users.getUserPrivOther().contains("170,")){
            json.setObject(true);
        }else {
            json.setObject(false);
        }
        json.setTotleNum(documentReceiveMapper.queryCount(map));
        json.setObj(query);
        json.setFlag(0);
        return json;
    }

    private List getAttachAndDoc(String sqlType, Integer fromRunId) {
        List<Attachment> result = new ArrayList<>();
        // 先去公文  获取公文正文
        DocumentModelWithBLOBs documentModel=documentModelMapper.checkRunIds(fromRunId);
        try {
            if(!StringUtils.checkNull(documentModel.getMainAipFile())){//若有pdf文件，则显示pdf文件
                List<Attachment> pdf = GetAttachmentListUtils.returnAttachment(documentModel.getMainAipFileName(), documentModel.getMainAipFile(), sqlType, "document");
                result.add(pdf.get(0));
                if(!StringUtils.checkNull(documentModel.getMainClearFile())){//若是正文转的pdf，则把清稿正文显示
                    List<Attachment> clear = GetAttachmentListUtils.returnAttachment(documentModel.getMainClearFileName(), documentModel.getMainClearFile(), sqlType, "document");
                    result.add(clear.get(0));
                }
            }else{//若不是pdf文件，就显示当前编辑的word文件
                List<Attachment> mainFile = GetAttachmentListUtils.returnAttachment(documentModel.getMainFileName(), documentModel.getMainFile(), sqlType, "document");
                result.add(mainFile.get(0));
            }
        }catch (Exception e){

        }

        return result;
    }

    //公文补发，读取出没有分发的单位
    @Override
    public ToJson reinsertDocumentReceive(String unitType, Integer fromRunId) {
        ToJson json = new ToJson<>();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        String receiveExchangeDeptId = "";
        String exchangeDeptId = "";
        List<DocumentExchangeReceive> documentExchangeReceives = documentReceiveMapper.selectByRunId(fromRunId);//获取已经分发过的DEPT_ID串
        for (
                DocumentExchangeReceive doc : documentExchangeReceives
        ) {
            if(!StringUtils.checkNull(String.valueOf(doc.getExchangeId()))){
                receiveExchangeDeptId = receiveExchangeDeptId + doc.getExchangeId() + ",";
            }
        }
        Map<String, Object> map = new HashMap<>();
        DocumentExchangeSet documentExchangeSet = new DocumentExchangeSet();
        documentExchangeSet.setDocumentPriv("1");
        documentExchangeSet.setUnitType(unitType);
        map.put("obj", documentExchangeSet);
        Map<String, List<DocumentExchangeSet>> maps = new HashMap();
        List<DocumentExchangeSet> documentExchangeSets = documentExchangeSetMapper.selectByExample(map);
        List<DocumentExchangeSet> documentExchangeSets1 = documentExchangeSetMapper.selectAllByPriv();
        Boolean res = true;
        //取出所有符合的depts
        String depts = "";//符合的所有部门
        for (DocumentExchangeSet des : documentExchangeSets1) {
            depts = depts + des.getExchangeDeptId() + ",";
        }
        //判断公文设置的当前登陆人是否含有子部门
        for (DocumentExchangeSet des : documentExchangeSets1) {
            String[] exchangeUserId = des.getExchangeUserId().split(",");
            if (Arrays.asList(exchangeUserId).contains(user.getUserId()) && des.getChildDepts() != null && des.getChildDepts() != "") {//判断是否由子部门
                String[] childDepts = des.getChildDepts().split(",");
                for (int i = 0; i < childDepts.length; i++) {
                    if (Arrays.asList(depts.split(",")).contains(childDepts[i])) {
                        DocumentExchangeSet dpo = new DocumentExchangeSet();
                        dpo.setExchangeDeptId(Integer.parseInt(childDepts[i]));
                        maps.put("obj", documentExchangeSetMapper.selectByExchangeDeptId(dpo));
                    }
                }
                res = false;//若有子部门，则不筛选其他部门
                break;
            }
        }
        if (res) {
            maps.put("obj", documentExchangeSets);
        }
        List<DocumentExchangeSet> obj = maps.get("obj");
        for (DocumentExchangeSet dt:obj
             ) {
            exchangeDeptId=exchangeDeptId+(dt.getExchangeId()+",");
        }
        //算法将两个串中的重复数据删掉
        String[] arr1 = exchangeDeptId.split(",");
        String[] arr2 = receiveExchangeDeptId.split(",");
        for (int i = 0; i < arr2.length; i++) {
            for (int j = 0; j < arr1.length; j++) {
                if (arr1[j].equals(arr2[i])) {
                    arr1[j] = "";
                }
            }
        }
        StringBuffer sb = new StringBuffer();
        for (int j = 0; j < arr1.length; j++) {
            if (!"".equals(arr1[j])) {
                sb.append(arr1[j] + ",");
            }
        }
        if (sb.toString().length() > 0) {
            String[] exchangeIds = sb.toString().substring(0, sb.toString().length() - 1).split(",");
            Map<String,Object> map2=new HashMap<>();
            map2.put("exchangeIds",exchangeIds);
            List<DocumentExchangeSet> documentExchangeSets2 = documentExchangeSetMapper.selectByExchangeIds(map2);
            maps.put("obj",documentExchangeSets2);
        }else{
            maps.put("obj",null);
        }

        json.setObject(maps);
        json.setFlag(0);
        //当前登录人的单位
        json.setObj(documentExchangeSetMapper.selectByUser(user.getUserId()));
        return json;
    }

    @Override
    public ToJson<DocumentExchangeReceive> receiveDoc(DocumentExchangeReceive documentExchangeReceive, HttpServletRequest request) {
        ToJson<DocumentExchangeReceive> json = new ToJson<>();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        documentExchangeReceive.setReceiveUser(users.getUserId());
        documentExchangeReceive.setReceiveTime(new Date());
        documentExchangeReceive.setReceiveStatus("1");
        documentReceiveMapper.updateByPrimaryKeySelective(documentExchangeReceive);
        json.setFlag(0);
        return json;
    }
    //内部公文收回
    @Override
    public ToJson recoverDoc(HttpServletRequest request){
        String[] receiveId = (request.getParameter("receiveId")).split(",");
        ToJson json=new ToJson();
        int num=0;
        for (String id:receiveId) {
            DocumentExchangeReceive documentExchangeReceive=new DocumentExchangeReceive();
            documentExchangeReceive.setReceiveStatus("2");
            documentExchangeReceive.setReceiveId(Integer.parseInt(id));
            num+=documentReceiveMapper.updateByPrimaryKeySelective(documentExchangeReceive);
        }
        if(num>0){
            json.setFlag(0);
            json.setObject("收回"+num+"条数据");
        }else{
            json.setFlag(1);
            json.setObject("收回失败");
        }
        return json;
    }
    //根据主键获取数据
    @Override
    public ToJson queryById(DocumentExchangeReceive documentExchangeReceive){
        ToJson json=new ToJson();
        DocumentExchangeReceive documentExchangeReceive1 = documentReceiveMapper.selectByPrimaryKey(documentExchangeReceive.getReceiveId());
        if(documentExchangeReceive1!=null){
            json.setMsg("ok");
            json.setFlag(0);
            json.setObject(documentExchangeReceive1);
        }else{
            json.setMsg("无数据");
            json.setFlag(1);
        }
        return json;
    }

    @Override
    public ToJson queryByReturn(HttpServletRequest request, String receiveStatus, Integer page, Integer limit, boolean useFlag) {
        ToJson json = new ToJson();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        Map map = new HashMap();
        PageParams pageParams = new PageParams(useFlag,page,limit);
        map.put("pageParams",pageParams);
        map.put("userId",users.getUserId());
        map.put("receiveStatus",receiveStatus);
        List<DocumentExchangeReceive> list  = documentReceiveMapper.queryByReturn(map);
        for (DocumentExchangeReceive doc:list) {
            if(!StringUtils.checkNull(doc.getReceiveUser())){
                doc.setReceiveUser(usersMapper.getUsernameByUserId(doc.getReceiveUser()));
            }
        }
        json.setFlag(0);
        json.setObj(list);
        return json;
    }
}
